/**
 * projects store
 * manage all states of projects
 * @author Huihua Lu
 */
import {
  Module,
  Mutation,
  VuexModule,
  getModule,
  Action,
} from 'vuex-module-decorators'
import store from '@/store'
import DataViewStore from '@/store/modules/dataview'
import {
  queryAllProjects,
  copyProjectById,
  deleteProjectById,
  createProject,
  queryProjectById,
  updateProjectInfoById,
  // 新接口
  changeStatus,
  queryRoleByProjectId,
  addRole,
  deleteRoleById,
  updateProjectRole,
  queryRoleList,
  copyTemplateProjectById,
} from '@/api/home'

import { queryInfoByName } from '@/api/user'
import { message } from 'ant-design-vue'

// 项目
export interface Project {
  id: number
  name: string
  lock?: number
  type: number
  description?: string
  auth?: number
  creatorName?: string
  gmtCreate?: string
  gmtCreator?: string
  gmtModifier?: string
  gmtModify?: string
}

// 权限
export interface Auth {
  gmtModify: string
  id: number
  auth: number
  roleId: number
  projectId: number
  userId: number
  userName: string
  roleName: string
}

// 成员信息
export interface MemberInfo {
  id?: number
  name: string
  email?: string
  password?: string
  phone?: string
  remark?: string
  status?: string
  gmtCreate?: string
  gmtCreator?: string
  gmtModifier?: string
  gmtModify?: string
}

@Module({ dynamic: true, namespaced: true, name: 'ProjectStore', store })
class ProjectStore extends VuexModule {
  private _projects: Array<Project> = [] // 当前用户所有项目

  private _totalElements: number = 0 // 当前项目总数

  private _projectStatus: number = 0 // 当前项目是否可修改 0-正常  1-锁定

  private _activeProject: Project | null = null // 当前操作项目

  private _projectAuth: Array<Auth> = [] // 当前项目所有权限记录

  private _projectMembers: Array<MemberInfo> = [] // 所有可以选择加入项目的成员

  private _addMemberModalVisible: boolean = false // 是否显示添加成员弹窗

  private _isCardMode: boolean = true // 是否以卡片形式显示项目

  private _roleList: any = [] // 权限列表

  public get projects() {
    return this._projects
  }

  public get totalElements() {
    return this._totalElements
  }

  public get projectStatus() {
    return this._projectStatus
  }

  public get activeProject() {
    return this._activeProject
  }

  public get projectAuth() {
    return this._projectAuth
  }

  public get projectMembers() {
    return this._projectMembers
  }

  public get addMemberModalVisible() {
    return this._addMemberModalVisible
  }

  public get isCardMode() {
    return this._isCardMode
  }

  public get roleList() {
    return this._roleList
  }

  // 获取当前用户的所有项目
  @Action({ commit: 'setProjects' })
  public async loadProjects(postData: any) {
    const response = await queryAllProjects({ data: postData })
    this.context.commit(
      'setTotalElements',
      response.data.result.totalElements
        ? response.data.result.totalElements
        : 0
    )
    return response.data.result.data ? response.data.result.data : []
  }

  // 修改当前项目的状态
  @Action({ commit: 'setProjectStatus' })
  public async changeProjectStatus(passData: any) {
    const response = await changeStatus({ data: passData })
    if (response.data.code === 100) {
      message.success('项目状态修改成功')
    }
    return passData.lock
  }

  // 复制项目
  @Action({ commit: 'setProjects' })
  public async copyProject(passData: any) {
    const loadingMessage = message.loading('项目复制中...', 0)

    const postData = {
      projectId: passData.projectId,
    }
    const result = await copyProjectById({ data: postData })
    if (result.data.code === 100) {
      loadingMessage()
      message.success('项目复制成功')
    } else {
      loadingMessage()
      message.warning(result.data.message)
    }

    const response = await queryAllProjects({ data: passData.queryData })
    this.context.commit(
      'setTotalElements',
      response.data.result.totalElements
        ? response.data.result.totalElements
        : 0
    )
    return response.data.result.data ? response.data.result.data : []
  }

  // 复制模板项目
  @Action({ commit: 'setProjects' })
  public async copyTemplateProject(passData: any) {
    const loadingMessage = message.loading('项目复制中...', 0)

    const postData = {
      projectId: passData.projectId,
    }
    const result = await copyTemplateProjectById({ data: postData })
    if (result.data.code === 100) {
      loadingMessage()
      message.success('项目复制成功')
    } else {
      loadingMessage()
      message.warning(result.data.message)
    }

    const response = await queryAllProjects({ data: passData.queryData })
    this.context.commit(
      'setTotalElements',
      response.data.result.totalElements
        ? response.data.result.totalElements
        : 0
    )
    return response.data.result.data ? response.data.result.data : []
  }

  // 删除项目
  @Action({ commit: 'setProjects' })
  public async deleteProject(passData: any) {
    const postData = {
      id: passData.projectId,
    }
    const result = await deleteProjectById({ data: postData })
    if (result.data.code === 100) {
      message.success('项目删除成功')
    }

    const response = await queryAllProjects({ data: passData.queryData })
    this.context.commit(
      'setTotalElements',
      response.data.result.totalElements
        ? response.data.result.totalElements
        : 0
    )
    return response.data.result.data ? response.data.result.data : []
  }

  // 创建项目
  @Action
  public async createNewProject(passData: any) {
    console.log(passData)
    const result = await createProject({ data: passData.data })
    if (result.data.code === 100) {
      message.success('项目创建成功')
    } else {
      throw new Error('创建失败')
    }
    console.log(passData.queryData)
    // const response = await queryAllProjects({ data: passData.queryData })
    // this.context.commit(
    //   'setTotalElements',
    //   response.data.result.totalElements
    //     ? response.data.result.totalElements
    //     : 0
    // )
    // return response.data.result.data ? response.data.result.data : []
  }

  // 获取当前项目所有有权限的成员名单
  @Action({ commit: 'setProjectAuth' })
  public async queryProjectAuth(id: number | null) {
    if (!id) {
      return []
    }

    const postData = {
      projectId: id,
    }
    const response = await queryRoleByProjectId({ data: postData })
    return response.data.result
  }

  // 修改成员权限
  @Action({ commit: 'setProjectAuth' })
  public async updateAuth(newAuth: any) {
    await updateProjectRole({ data: newAuth }).then((response) => {
      if (response.data.code === 100) {
        message.success('权限修改成功！')
      }
    })

    const postData = {
      projectId: this._activeProject?.id,
    }
    const responseRole = await queryRoleByProjectId({ data: postData })
    return responseRole.data.result
  }

  // 删除项目成员
  @Action({ commit: 'setProjectAuth' })
  public async deleteAuth(passData: any) {
    if (passData.id === null) {
      return this._projectAuth
    }

    await deleteRoleById({ data: passData }).then((response) => {
      if (response.data.code === 100) {
        message.success('成员删除成功')
      }
    })

    const postData = {
      projectId: this._activeProject?.id,
    }
    const responseRole = await queryRoleByProjectId({ data: postData })
    return responseRole.data.result
  }

  // 获取所有可以选择的成员名单
  @Action({ commit: 'setProjectMembers' })
  public async getAllProjectMembers() {
    const passData: MemberInfo = {
      name: '',
    }
    const response = await queryInfoByName({ data: passData })

    return response.data.result
  }

  // 添加项目新成员
  @Action({ commit: 'setProjectAuth' })
  public async createNewAuth(passData: any) {
    const response1 = await addRole({ data: passData })
    if (response1.data.code === 100) {
      message.success('成员添加成功')
    } else if (response1.data.success === false) {
      message.warning(response1.data.message)
    }
    // console.log(response1)

    const postData = {
      projectId: this._activeProject?.id,
    }
    const response = await queryRoleByProjectId({ data: postData })
    return response.data.result
  }

  // 获取项目信息
  @Action({ commit: 'setActiveProject' })
  public async queryProjectById(id: string) {
    const response = await queryProjectById({ data: { id } })
    DataViewStore.setLock(response.data.result.lock === 1)
    return response.data.result
  }

  // 修改项目信息
  @Action({ commit: 'setActiveProject' })
  public async updateProjectInfoById(passData: any) {
    const response = await updateProjectInfoById({ data: passData })
    if (response.data.code === 100) {
      DataViewStore.setLock(response.data.result.lock === 1)
      message.success('项目信息修改成功')
    } else {
      message.error(`Error ${response.data.code}: ${response.data.message}`)
    }
    return response
  }

  @Action({ commit: 'setRoleList' })
  public async getRoleList() {
    const response = await queryRoleList()
    return response.data.result
  }

  @Mutation
  private setRoleList(value: any) {
    this._roleList = value
  }

  @Mutation
  private setProjects(projects: Array<Project>) {
    this._projects = projects
  }

  @Mutation
  private setTotalElements(value: number) {
    this._totalElements = value
  }

  @Mutation
  private setProjectStatus(lock: number) {
    this._projectStatus = lock
  }

  @Mutation
  public clearActiveProject() {
    this._activeProject = null
  }

  @Mutation
  public setActiveProject(project: Project) {
    this._activeProject = project
  }

  @Mutation
  private setProjectAuth(auths: Array<Auth>) {
    this._projectAuth = auths
  }

  @Mutation
  private setProjectMembers(members: Array<MemberInfo>) {
    this._projectMembers = members
  }

  @Mutation
  public setAddMemberModalVisible(isVisible: boolean) {
    this._addMemberModalVisible = isVisible
  }

  @Mutation
  public setIsCardMode(isCard: boolean) {
    this._isCardMode = isCard
  }

  @Mutation
  public clearState() {
    this._projects = []
    this._activeProject = null
    this._projectAuth = []
    this._projectMembers = []
    this._addMemberModalVisible = false
  }
}

export default getModule(ProjectStore)
